package com.ifyyf.test.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author if
 * @Description: 版本号机制
 * 注意如果这里写Integer的话，只能采用-127~128的区间
 * 因为底层是采用的==判断！！！！！
 * expectedReference == current.reference
 *
 * @Date 2021-11-09 下午 04:33
 */
public class CASDemo {
    public static void main(String[] args) {
        AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(1, 1);

        new Thread(()->{
            //获取版本号
            int stamp = atomicInteger.getStamp();
            System.out.println("一开始的A - stamp = " + stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("A -> "+atomicInteger.compareAndSet(1, 2, stamp, (stamp + 1)));
            System.out.println("结束的的A - stamp = " + atomicInteger.getStamp());
            System.out.println("=======================");
        },"A").start();

        new Thread(()->{
            int stamp = atomicInteger.getStamp();
            System.out.println("B - stamp = " + stamp);
            System.out.println("B -> "+atomicInteger.compareAndSet(1, 2, stamp, stamp + 1));
            System.out.println("结束的的B - stamp = " + atomicInteger.getStamp());
            System.out.println("=======================");
        },"B").start();


        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("最后getStamp = "+atomicInteger.getStamp());
        System.out.println("atomicInteger值 = "+atomicInteger.get(new int[]{atomicInteger.getStamp()}));
    }
}
